package com.smartrm.globalinfrcore.event.impl;

import com.smartrm.globalinfrcore.event.DomainEvent;
import com.smartrm.globalinfrcore.event.DomainEventBus;
import com.smartrm.globalinfrcore.event.DomainHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/*
 * @program: common-starters
 * @description: 事件总线默认实现
 * @author: houhong
 * @create: 2023-01-10 15:19
 */
@Component
public class DefaultDomainEventBusImpl implements DomainEventBus, ApplicationContextAware {

    private static final Logger logger = LoggerFactory.getLogger(DefaultDomainEventBusImpl.class);

    private ApplicationContext applicationContext;

    //// TODO: 2023/1/10 集成rocketMq 作为消息总线

    @Override
    public void post(DomainEvent event) {

        logger.info("【domain-bus】publish event :{}", event.getEventName());
        applicationContext.publishEvent(event);
        //发布消息 使用MQ 生成消息总线，在跨微服务中使用
        logger.info("【domain-bus】publish messages :{}", event.getEventName());
    }

    @Override
    public void register(DomainHandler domainHandler) {
        ConfigurableApplicationContext configurableApplication = (ConfigurableApplicationContext) applicationContext;
        configurableApplication.addApplicationListener(domainHandler);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}